package com.imooc.mall.controller;

import com.imooc.mall.common.ResultInfo;
import com.imooc.mall.dto.CartDto;
import com.imooc.mall.dto.CartUpdateDto;
import com.imooc.mall.form.CartAddForm;
import com.imooc.mall.pojo.User;
import com.imooc.mall.service.ICartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import static com.imooc.mall.common.MallConst.CURRENT_USER;

@RestController
@RequestMapping("/cart")
@Slf4j
public class CartController {

    @Autowired
    private ICartService cartService;

    @PostMapping("/add")
    public ResultInfo<CartDto> add(@RequestBody @Valid CartAddForm cartAddForm, HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute(CURRENT_USER);
        log.info("添加购物车==>>用户：{},商品：{}",user.getId(),cartAddForm.getProductId());
        return cartService.add(cartAddForm,user.getId());
    }
    @GetMapping("/list")
    public ResultInfo<CartDto> list(HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute(CURRENT_USER);
        log.info("查看购物车==>>用户：{}",user.getId());
        return cartService.list(user.getId());
    }
    @PutMapping("/update/{productId}")
    public ResultInfo<CartDto> list(@PathVariable Integer productId,@RequestBody CartUpdateDto cartUpdateDto,HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute(CURRENT_USER);
        log.info("更新购物车==>>用户：{}",user.getId());
        return cartService.update(user.getId(),productId,cartUpdateDto);
    }
    @DeleteMapping("/delete/{productId}")
    public ResultInfo<CartDto> delete(@PathVariable Integer productId,HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute(CURRENT_USER);
        log.info("更新购物车==>>用户：{}",user.getId());
        return cartService.delete(user.getId(),productId);
    }



    @PutMapping("/selectAll")
    public ResultInfo<CartDto> selectAll(HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute(CURRENT_USER);
        log.info("购物车全选==>>用户：{}",user.getId());
        return cartService.selectAll(user.getId());
    }
    @PutMapping("/unSelectAll")
    public ResultInfo<CartDto> unSelectAll(HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute(CURRENT_USER);
        log.info("购物车全不选==>>用户：{}",user.getId());
        return cartService.unSelectAll(user.getId());
    }
    @GetMapping("/sum")
    public ResultInfo<Integer> sum(HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute(CURRENT_USER);
        log.info("购物车统计商品数==>>用户：{}",user.getId());
        return cartService.sum(user.getId());
    }

}
